<template>
    <el-dialog :model-value="show" title="添加用户" @close="emit('hide')">
        <el-form ref="ruleFormRef" :model="form" :rules="rules">
            <el-form-item label="账号：" prop="username">
                <el-input v-model="form.username" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="姓名：" prop="nickName">
                <el-input v-model="form.nickName" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="邮箱：" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
                <el-input v-model="form.password" type="password" placeholder="请输入密码" :disabled="id !== 0" />
            </el-form-item>
            <el-form-item label="备注：">
                <el-input v-model="form.note" :rows="2" type="textarea" placeholder="请输入备注" />
            </el-form-item>
            <el-form-item label="是否启用">
                <el-radio-group v-model="form.status" class="ml-4">
                    <el-radio label="1" size="large">是</el-radio>
                    <el-radio label="0" size="large">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="emit('hide')">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { addUserAPI, getUserIdAPI, updateUserAPI } from "./api/admin"
const ruleFormRef = ref<FormInstance>()

const editUser = () => {
    ElMessageBox.confirm("确定要修改当前用户的修改吗", "修改用户信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        updateUserAPI(form).then((res) => {
            if (res.code === 200) {
                ElMessage.success("修改成功");
                // 清空表单
                ruleFormRef.value?.resetFields();
                emit("hide", true)
            }
        })
    }).catch(() => { })
}

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    id: {
        type: Number,
        default: 0
    }
})

// console.log(props.id);

// 监听props.id有没有发生变化，
// 如果 id !== 0 就是编辑用户，如果id ===  0 就是添加用户
watch(
    () => props.id,
    () => {
        if (props.id !== 0) {
            getUserIdAPI(props.id).then((res) => {
                if (res.code === 200) {
                    // 合并数据
                    Object.assign(form, res.data)
                }
            })
        }
    }
)


const emit = defineEmits(["hide"])

const form = reactive<IUserModel>({
    username: "",
    nickName: "",
    email: "",
    password: "",
    note: "",
    status: 0,

})
const validateEmail = (rules: any, value: string, callback: any) => {
    // 验证value是否是一个邮箱
    if (!/^\w+[@]\w+[.]\w+/.test(value)) {
        return callback(new Error("邮箱格式不正确"))
    } else {
        callback();
    }
}

const rules = {
    username: [{ required: true, trigger: "blur", message: "请填写用户名" }],
    nickName: [{ required: true, trigger: "blur", message: "请填写姓名" }],
    password: [{ required: true, trigger: "blur", message: "请填写密码" }],
    email: [{ required: true, validator: validateEmail, trigger: "blur" }]
}

const submitForm = () => {
    // 数据校验
    ruleFormRef.value?.validate((ok: boolean) => {
        if (ok) {
            if (props.id === 0) {
                ElMessageBox.confirm("确定要添加用户吗", "添加用户", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                }).then(() => {
                    // 发请求
                    addUserAPI(form).then(res => {
                        if (res.code === 200) {
                            // 提示
                            ElMessage.success("用户添加成功")
                            // 把dialog关闭
                            emit('hide')
                            // 刷新数据
                            // 清空表单
                            ruleFormRef.value?.resetFields();
                        }
                    })

                }).catch(() => {
                    // console.log("点击的取消");
                })
            } else if (props.id !== 0) {
                editUser();
            }


        } else {
            // 提示
            ElMessage.error("用户添加失败")
        }
    })
}
</script>
<style lang="less" scoped>

</style>